package com.hyving.home.jpamulti.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Objects;

@Configuration
@EnableTransactionManagement //开启生明式事务
@EnableConfigurationProperties(JpaProperties.class)
@EnableJpaRepositories( //用来扫描指定的包及其子包中repository定义
        value="com.hyving.home.jpamulti.repository.primary",
        entityManagerFactoryRef="primaryEntityManagerFactory",
        transactionManagerRef="primaryTransactionManager")//设置dao层（持久层，即repo）所在位置
public class PrimaryDataConfig {

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource; //注入主配置类中的主数据源

    /**
     * 实体管理工厂的bean
     */
    @Bean(name = "primaryEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDataSource)
                //这个是指向你的domain, entity的路径。 实体类所在的包
                .packages("com.hyving.boot.dynamic.jpa.repository.primary")
                .persistenceUnit("primary")
                .build();
    }


    /**
     * 配置 实体管理器
     */
    @Bean
    @Primary
    public EntityManager primaryEntityManager(@Qualifier("primaryEntityManagerFactory")EntityManagerFactory factory){
        return  factory.createEntityManager();
    }


    /**
     * 配置事务管理
     */
    @Bean(name = "primaryTransactionManager")
    @Primary
    public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryEntityManagerFactory") EntityManagerFactory factory) {
        return new JpaTransactionManager(factory);
    }
}
